package com.huichenghe.xinlvsh01;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Telephony;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.huichenghe.xinlvsh01.Adapter.MainPagerRecyclerAdapter;
import com.huichenghe.xinlvsh01.Ble.BleDataForBattery;
import com.huichenghe.xinlvsh01.Ble.BleDataForDayData;
import com.huichenghe.xinlvsh01.Ble.BleDataForDayHeartReatData;
import com.huichenghe.xinlvsh01.Ble.BleDataForEachHourData;
import com.huichenghe.xinlvsh01.Ble.BleDataForHardVersion;
import com.huichenghe.xinlvsh01.Ble.BleDataForSleepData;
import com.huichenghe.xinlvsh01.Ble.BleDataforSyn;
import com.huichenghe.xinlvsh01.Ble.BleForPhoneAndSmsRemind;
import com.huichenghe.xinlvsh01.Ble.BleNotifyParse;
import com.huichenghe.xinlvsh01.Ble.BluetoothLeService;
import com.huichenghe.xinlvsh01.Ble.DeviceConfig;
import com.huichenghe.xinlvsh01.Ble.Engine;
import com.huichenghe.xinlvsh01.Ble.IServiceCallback;
import com.huichenghe.xinlvsh01.Ble.LocalDeviceEntity;
import com.huichenghe.xinlvsh01.CustomView.CircleImageView;
import com.huichenghe.xinlvsh01.CustomView.CustomChooseTypeDialog;
import com.huichenghe.xinlvsh01.DataEntites.OutLineDataEntity;
import com.huichenghe.xinlvsh01.DbEntities.DeviceSaveData;
import com.huichenghe.xinlvsh01.DbEntities.LocalDataBaseUtils;
import com.huichenghe.xinlvsh01.DbEntities.MyDBHelperForDayData;
import com.huichenghe.xinlvsh01.Utils.BreakPhoneUtils;
import com.huichenghe.xinlvsh01.Utils.LocalDataSaveTool;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;
import com.huichenghe.xinlvsh01.Utils.MyToastUitls;
import com.huichenghe.xinlvsh01.Utils.SaveImageUtil;
import com.huichenghe.xinlvsh01.Utils.ShotScreenForShare;
import com.huichenghe.xinlvsh01.expand_activity.Detail_activity;
import com.huichenghe.xinlvsh01.expand_activity.ShareActivity;
import com.huichenghe.xinlvsh01.expand_activity.TargetSettingActivity;
import com.huichenghe.xinlvsh01.expand_activity.TrendActivity;
import com.huichenghe.xinlvsh01.slide.AboutActivity;
import com.huichenghe.xinlvsh01.slide.DeviceAmdActivity;
import com.huichenghe.xinlvsh01.slide.EditPersionInfoActivity;
import com.huichenghe.xinlvsh01.slide.HelpActivity;
import com.huichenghe.xinlvsh01.slide.LoginActivity;
import com.huichenghe.xinlvsh01.slide.RemindActivity;
import com.huichenghe.xinlvsh01.slide.Sub_login;
import com.huichenghe.xinlvsh01.zhy.utils.nextToLoginActivity;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity implements IServiceCallback
{

	public static final String TAG = "MainActivity";
	public static MainActivity instance = null;
	private RelativeLayout remindA;
	private TextView tvConState, tvBattery;
	private static final int MSG_SYNC_TIME = 0;            // 同步时间
	private static final int MSG_GET_DEVICE_VERSION = 1;// 版本号
	private static final int MSG_GET_DEVICE_BATTERU = 2;// 电量
	private static final int MSG_GET_DAY_DATA = 3;        // 全天数据
	private static final int MST_GET_ALL_HEARTREAT_DATA = 4;    // 全天心率
	private static final int MSG_GET_EACH_HOUR_DATA = 5;        // 分时运动数据
	private static final int MSG_GET_SLEEP_DATA = 6;            // 睡眠数据

	private ImageView movementI;
	private LinearLayout mLinearLayout;
	private RelativeLayout layoutOne;
	private CoordinatorLayout layoutTwo;


	private LinearLayout bottom_left;
	private TextView botton_right;

	private TextView accountText, nickText, logOut;
	private boolean isLoginTrue = false;
	private TextView stepAllTv, calorieTv, targetTv, movementTimeTv, mileageTv, completeTv;

	private ArrayList<OutLineDataEntity> dataList;    // 离线数据集合
	private MainPagerRecyclerAdapter itemAdapter;    // 离线数据适配器


	private SlidingMenu mMenu;                  // 侧拉菜单对象
	private RelativeLayout device_adm, aboutA, helpA;// 设备管理
	private CircleImageView persionInfo;      // 圆形头像
	private SmsReciver reciver;


	// 线程通信对象
	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_SYNC_TIME:                // 同步时间
					Log.i(TAG, "执行synTime");
					new BleDataforSyn().syncCurrentTime();
					break;

				case MSG_GET_DEVICE_BATTERU:    // 获取电量
					Log.i(TAG, "获取电量battey");
					new BleDataForBattery();    // 发送获取电量
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							int battery = BleDataForBattery.getmCurrentBattery();    // 获取电量
							updateBattery(battery);        // 更新电量
							Log.i(TAG, "battery：" + battery);
						}
					}, 1000);
					break;

				case MSG_GET_DEVICE_VERSION:    // 获取固件版本号
					new BleDataForHardVersion();
//					mHandler.postDelayed(new Runnable()
//					{
//						@Override
//						public void run()
//						{
//
//						}
//					}, 1000);
					break;
				case MSG_GET_DAY_DATA:            // 获取当天数据

					new BleDataForDayData().requestDayDate();
					break;

				case MST_GET_ALL_HEARTREAT_DATA:
					// 发送数据获取全天心率


					new GetEachHourTask().execute(2);

					break;

				case MSG_GET_EACH_HOUR_DATA:
					// 获取分时数据
					new GetEachHourTask().execute(1);
					break;

				case MSG_GET_SLEEP_DATA:

					new GetSleepDataTask().execute();


					break;
			}


		}
	};
	/**
	 * ATTENTION: This was auto-generated to implement the App Indexing API.
	 * See https://g.co/AppIndexing/AndroidStudio for more information.
	 */
	private GoogleApiClient client;

	/**
	 * 更新电量显示
	 *
	 * @param battery
	 */
	private void updateBattery(int battery) {
		if (battery >= 0) {
			tvBattery.setText(battery + "%");
		} else {
			tvBattery.setText("X");
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题
		setContentView(R.layout.activity_main);
		instance = this;
		init();
		InitBluetooth();                    // 初始化蓝牙相关
		registBroatcast();
		Engine.getInstance().init(this.getApplicationContext());

//		String a = MyDBHelperForDayData.getInstance(MainActivity.this).getDataBaseName();
//		MyDBHelperForDayData.insert(MainActivity.this, "lixiaoning", "12月12号", "ok");
////		MyDBHelperForDayData.getInstance(MainActivity.this).getMyWritableDatabase();
//		Log.i(TAG, "数据库的名字：" + a);
//		MyDBHelperForDayData.getInstance(MainActivity.this).insert(MainActivity.this, "lixiaoning",
//				"2015-8-8", "two", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
		LocalDataSaveTool.getInstance(this).writeSp(MyConfingInfo.TARGET_SETTING_VALUE, String.valueOf(10000));

		readDbAndshow();        // 读取数据库离线运动，并显示
		updateThisScreen();        // 读取全天数据，并显示

		registCallingListener();

		registBroacastForSms();
		// ATTENTION: This was auto-generated to implement the App Indexing API.
		// See https://g.co/AppIndexing/AndroidStudio for more information.
		client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
	}

	private void registBroacastForSms() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.provider.Telephony.SMS_RECEIVED");
		reciver = new SmsReciver();
		registerReceiver(reciver, filter);
	}

	private void unregistSms()
	{
		unregisterReceiver(reciver);
	}


	/**
	 * 监听来电
	 */
	private void registCallingListener()
	{
		// 电话管理类
		TelephonyManager PhoneManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		// 电话状态监听类
		PhoneStateListener listenerM = new PhoneStateListener()
		{
			@Override
			public void onCallStateChanged(int state, String incomingNumber)
			{
				boolean isNeedRemind = false;
				String phoneR = LocalDataSaveTool.getInstance(MainActivity.this).readSp(MyConfingInfo.PHONE_REMIND_CHANGE);
				if(phoneR.equals(MyConfingInfo.REMIND_OPEN))		// 判断缓存中的提醒是否打开
				{
					isNeedRemind = true;
				}
				switch (state)
				{
					case TelephonyManager.CALL_STATE_IDLE:// 空闲状态
						break;

					case TelephonyManager.CALL_STATE_RINGING:// 来电,正在响铃
						Log.i(TAG, "来电中。。。。");
						if(isNeedRemind)	// 提醒是打开的
						{
							// 先打开手环的来电提醒功能
							BleForPhoneAndSmsRemind bfp = new BleForPhoneAndSmsRemind();
							bfp.openThePhoneAndSmsRemind((byte) 0x03);
//							 读取联系人
							String name = BreakPhoneUtils.getContactNameFromPhoneBook(MainActivity.this, incomingNumber);
//							 发送数据

							bfp.startPhoneAndSmsRemind(incomingNumber, name, BleForPhoneAndSmsRemind.startPhoneRemindToDevice);


						}



						break;

					case TelephonyManager.CALL_STATE_OFFHOOK:// 接起电话




				}

				super.onCallStateChanged(state, incomingNumber);
			}
		};

		PhoneManager.listen(listenerM, PhoneStateListener.LISTEN_CALL_STATE);
	}


	boolean isFirstOpen = true;    // 首次打开app

	@Override
	protected void onResume() {
		super.onResume();
		if (isLoginTrue)    // 没有登陆，则登陆
		{
			new LoginOnBackground().execute((Void) null);
		}


		if (isFirstOpen) {
			openBle();
			isFirstOpen = false;
		}

		// 绑定service
		if (BluetoothLeService.getInstance() == null) {
			connectService();
		}

		// 读取缓存中的账号，昵称

		String account = LocalDataSaveTool.getInstance(this).readSp(MyConfingInfo.USER_ACCOUNT);
		String nick = LocalDataSaveTool.getInstance(this).readSp(MyConfingInfo.USER_NICK);
		if (account != null) {
			accountText.setText(account);
		}
		if (nick != null) {
			nickText.setText(nick);
		}


	}

	private void readDbAndshow() {
		Calendar calendar = Calendar.getInstance();
		Date d = calendar.getTime();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String day = format.format(d);
		String userAccount = LocalDataSaveTool.getInstance(MainActivity.this).readSp(MyConfingInfo.USER_ACCOUNT);
		MyDBHelperForDayData myHelper = MyDBHelperForDayData.getInstance(MainActivity.this);
		Cursor mCursor = myHelper.selectOutLineData(MainActivity.this, userAccount, day);
		Log.i(TAG, "查询结果：" + mCursor.getCount() + day);
		if (mCursor.getCount() != 0)        // 如果有数据
		{
			getTheDataFromCursor(mCursor);
		}

	}


	/**
	 * 遍历Cursor，取出数据并显示出来
	 *
	 * @param mCursor
	 */
	private void getTheDataFromCursor(Cursor mCursor) {//startTime, endTime, calorie, stepTotle
		if (mCursor.moveToFirst())        // 游标移动到开头
		{
			do {
				String startTime = mCursor.getString(mCursor.getColumnIndex("startTime"));
				String endTime = mCursor.getString(mCursor.getColumnIndex("endTime"));
				int calorie = mCursor.getInt(mCursor.getColumnIndex("calorie"));
				int stepTotle = mCursor.getInt(mCursor.getColumnIndex("stepTotle"));
				int type = mCursor.getInt(mCursor.getColumnIndex("type"));
				Log.i(TAG, "运动类型：" + type);
				int heartRate = mCursor.getInt(mCursor.getColumnIndex("heartRate"));

				dataList.add(new OutLineDataEntity(type, startTime + "-" + endTime, stepTotle, calorie, heartRate));

			} while (mCursor.moveToNext());    // 以有没有下一个数据为循环的判断标准

			itemAdapter.notifyDataSetChanged();


		}


	}


	/**
	 * 隐性登陆
	 */
	private boolean loginOnBackgrund() {
		boolean isSuccess = false;
		String account = LocalDataSaveTool.getInstance(this).readSp(MyConfingInfo.USER_ACCOUNT);
		String password = LocalDataSaveTool.getInstance(this).readSp(MyConfingInfo.USER_PASSWORD);
		Sub_login sub = new Sub_login(MainActivity.this);
		try {
			isSuccess = sub.requestLogin(account, password);
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (isSuccess) {
			return true;
		}

		return false;

	}

	@Override
	public void onStart() {
		super.onStart();

		// ATTENTION: This was auto-generated to implement the App Indexing API.
		// See https://g.co/AppIndexing/AndroidStudio for more information.
		client.connect();
		Action viewAction = Action.newAction(
				Action.TYPE_VIEW, // TODO: choose an action type.
				"Main Page", // TODO: Define a title for the content shown.
				// TODO: If you have web page content that matches this app activity's content,
				// make sure this auto-generated web page URL is correct.
				// Otherwise, set the URL to null.
				Uri.parse("http://host/path"),
				// TODO: Make sure this auto-generated app deep link URI is correct.
				Uri.parse("android-app://com.huichenghe.xinlvsh01/http/host/path")
		);
		AppIndex.AppIndexApi.start(client, viewAction);
	}

	@Override
	public void onStop() {
		super.onStop();

		// ATTENTION: This was auto-generated to implement the App Indexing API.
		// See https://g.co/AppIndexing/AndroidStudio for more information.
		Action viewAction = Action.newAction(
				Action.TYPE_VIEW, // TODO: choose an action type.
				"Main Page", // TODO: Define a title for the content shown.
				// TODO: If you have web page content that matches this app activity's content,
				// make sure this auto-generated web page URL is correct.
				// Otherwise, set the URL to null.
				Uri.parse("http://host/path"),
				// TODO: Make sure this auto-generated app deep link URI is correct.
				Uri.parse("android-app://com.huichenghe.xinlvsh01/http/host/path")
		);
		AppIndex.AppIndexApi.end(client, viewAction);
		client.disconnect();
	}


	private class LoginOnBackground extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			boolean isOk = loginOnBackgrund();
			return isOk;
		}

		@Override
		protected void onPostExecute(Boolean aBoolean) {
			if (aBoolean) {
				logOut.setVisibility(View.VISIBLE);
				botton_right.setVisibility(View.GONE);
				isLoginTrue = aBoolean;
			}

		}
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegistBroatcast();
		unregistSms();
	}

	//------------------------------------------------------------------------------------

	/**
	 * 打开蓝牙
	 */
	private void openBle() {
		if (BluetoothAdapter.getDefaultAdapter() != null && !BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			Boolean isOpenBle = BluetoothAdapter.getDefaultAdapter().enable();
			Log.i("", "蓝牙是否打开" + isOpenBle);
			showToast(R.string.make_sure, 1);
		}
	}


	/**
	 * 初始化蓝牙相关内容
	 */
	private void InitBluetooth() {
		// 检查手机是否支持蓝牙4.0
		if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
			showToast(R.string.ble_not_support, 1);
			finish();
			return;
		}
		// 检查手机是否支持蓝牙
		if (BluetoothAdapter.getDefaultAdapter() == null) {
			showToast(R.string.ble_not_support, 1);
			finish();
			return;
		}

	}

	//接收蓝牙适配器状态改变的系统广播
	private BroadcastReceiver mBluetoothStateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.e("", "接收到的action: " + action);
			if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
				int btState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
				Log.i("", "btState:" + btState);
				if (btState == BluetoothAdapter.STATE_ON)        // 手机蓝牙模块处于打开状态
				{
					onBluetoothModeOpen();
				} else if (btState == BluetoothAdapter.STATE_OFF)    // 模块处于关闭状态
				{
					onBluetoothModeClose();
				}
			} else if (MyConfingInfo.NOTIFY_MAINACTIVITY_TO_UPDATE_DAY_DATA.equals(action))    // 更新主页面的广播，从BleDataForDayData发送出来的
			{
				Log.i(TAG, "接收到存入当天数据的广播");
				updateThisScreen();
			} else if (MyConfingInfo.NOTIFY_MAINACTIVITY_TO_UPDATE_OUTLINE_DATA.equals(action)) {
				Log.i(TAG, "接收到存入离线数据的广播");
				updateOutLineData();
			}
		}
	};


	/**
	 * 更新主界面离线数据
	 */
	private void updateOutLineData() {
		String dat = null;
		Calendar calendar = Calendar.getInstance();
		int date = calendar.get(Calendar.DATE);
		if (date < 10) {
			dat = "0" + date;
		}
		int mon = calendar.get(Calendar.MONTH) + 1;
		int year = calendar.get(Calendar.YEAR);
		String day = year + "-" + mon + "-" + dat;


		Log.i(TAG, "MainActivity查询日期：" + day);
		String account = LocalDataSaveTool.getInstance(MainActivity.this).readSp(MyConfingInfo.USER_ACCOUNT);
		Cursor mCursor = MyDBHelperForDayData.getInstance(MainActivity.this)
				.selectOutLineData(MainActivity.this, account, day);

		Log.i(TAG, "MainActivity离线数据" + mCursor.getCount());
		if (mCursor.getCount() != 0) {
			Log.i(TAG, "有离线数据");
			ergodicCursor(mCursor);        // 遍历cursor,取出数据
		}
	}


	/**
	 * 遍历cursor取出数据
	 *
	 * @param mCursor startTime, endTime, calorie, stepTotle
	 */
	private void ergodicCursor(Cursor mCursor) {
		if (mCursor.moveToFirst()) {
			dataList.clear();// 先清空数据
			do {
				String startTime = mCursor.getString(mCursor.getColumnIndex("startTime"));
				String endTime = mCursor.getString(mCursor.getColumnIndex("endTime"));
				int calorie = mCursor.getInt(mCursor.getColumnIndex("calorie"));
				int stepTotal = mCursor.getInt(mCursor.getColumnIndex("stepTotle"));
				String time = startTime + "-" + endTime;
				dataList.add(new OutLineDataEntity(-1, time, stepTotal, calorie, 0));


			} while (mCursor.moveToNext());
		}


		Log.i(TAG, "更新离线数据界面");
		itemAdapter.notifyDataSetChanged();
	}


	/**
	 * 更新主界面的全天数据
	 * 通过账号和日期
	 */
	private void updateThisScreen() {
		Log.i(TAG, "更新显示");
		String account = LocalDataSaveTool.getInstance(MainActivity.this).readSp(MyConfingInfo.USER_ACCOUNT);
		Calendar calendar = Calendar.getInstance();
		String date = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DATE);
		MyDBHelperForDayData helper = MyDBHelperForDayData.getInstance(MainActivity.this);
		Cursor mCursor = helper.selecteDayData(MainActivity.this, account, date);
		Log.i(TAG, "全天数据查询出：" + mCursor.getCount());
		// 遍历Cursor
		if (mCursor.getCount() != 0)        // 有数据
		{
			if (mCursor.moveToFirst())        // 游标移动到开头
			{
				int stepFromDB;
				int calorieFromDB;
				int mileageFromDB;
				String movementTimeFromDB;
				String setTimeFromDB;
				do {
					stepFromDB = mCursor.getInt(mCursor.getColumnIndex("stepAll"));
					calorieFromDB = mCursor.getInt(mCursor.getColumnIndex("calorie"));
					mileageFromDB = mCursor.getInt(mCursor.getColumnIndex("mileage"));
					movementTimeFromDB = mCursor.getString(mCursor.getColumnIndex("movementTime"));
					setTimeFromDB = mCursor.getString(mCursor.getColumnIndex("sitTime"));

					Log.i(TAG, stepFromDB + "--" + calorieFromDB + "--" + "\r\n" + mileageFromDB + "--" + movementTimeFromDB + "--" + setTimeFromDB);

				} while (mCursor.moveToNext());

				mCursor.close();

				// 构建4h45'形式
				int moveTime = Integer.parseInt(movementTimeFromDB);
				int h = moveTime / 60;
				int m = moveTime % 60;

				// 将m换算成km
				float mileage = ((float) mileageFromDB) / 1000;
				// 四舍五入保留一位小数
				BigDecimal bd = new BigDecimal(mileage);
				bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
				Log.i(TAG, "元数据:" + mileageFromDB + "四舍五入前：" + mileage + "四舍五入后：" + bd.toString());

				// 计算完成度
				// 读取设置的目标
				String valueOfTarget = LocalDataSaveTool.getInstance(MainActivity.this).readSp(MyConfingInfo.TARGET_SETTING_VALUE);
				float targetF = (float) stepFromDB / (float) Integer.valueOf(valueOfTarget);
				targetF *= 100;


				setText(movementTimeTv, h + "h" + m + "'");
				setText(stepAllTv, String.valueOf(stepFromDB));
				setText(calorieTv, String.valueOf(calorieFromDB));
				setText(mileageTv, bd.toString());
				setText(completeTv, (int) targetF + "%");


			}

		}


	}

	private void setText(TextView tv, String s) {
		if (!s.isEmpty()) {
			tv.setText(s);
		}
	}

	/**
	 * 注册广播
	 */
	private void registBroatcast()
	{
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		filter.addAction(MyConfingInfo.NOTIFY_MAINACTIVITY_TO_UPDATE_DAY_DATA);
		filter.addAction(MyConfingInfo.NOTIFY_MAINACTIVITY_TO_UPDATE_OUTLINE_DATA);
		registerReceiver(mBluetoothStateReceiver, filter);

	}
	/*
	 *注销广播
	 */

	private void unRegistBroatcast()
	{
		unregisterReceiver(mBluetoothStateReceiver);
	}


	// 手机蓝牙打开
	private void onBluetoothModeOpen()
	{
		// 连接绑定服务对象
		connectService();
	}


	// 手机蓝牙关闭onBluetoothClose
	private void onBluetoothModeClose() {
	}

	/**
	 * 打开蓝牙并绑定Service
	 */
//	private BleServiceConnected mBleServiceConnected;	// 绑定服务回调借口实现类
	boolean haveBinded = false;                            // 标识绑定状态

	private void connectService() {
		if (BluetoothAdapter.getDefaultAdapter() != null
				&& BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			if (!haveBinded && mBleServiceConnected != null) {
//				mBleServiceConnected = new BleServiceConnected();
				// 与启动Activity相似,创建Intent
				Intent intent = new Intent(MainActivity.this, BluetoothLeService.class);
				// 传实现类,不然Service中将为null
				haveBinded = MainActivity.this.bindService(intent, mBleServiceConnected, Context.BIND_AUTO_CREATE);
				Log.i("", "BluetoothLeService已启动" + haveBinded);
			} else {
				Log.i("", "BluetoothLeService已启动并建立了连接,无需重复连接");
			}
		} else {
			showToast(R.string.make_sure, 1);// 提示打开蓝牙
		}


	}


	/**
	 * gatt监听借口的回调方法，此为gatt连接后在service中调用的
	 * @param device
	 * @param gatt
	 * @param list
	 */


	/**
	 * BluetoothLeService 中的gattcallback回调方法在底层调用后，回传gatt后，在回调方法内部调用此方法
	 *
	 * @param device 连接的设备信息实体对象
	 * @param gatt   建立的gatt连接对象
	 * @param list   手环的service列表
	 */
	@Override
	public void onBLEServiceFound(LocalDeviceEntity device,
								  BluetoothGatt gatt,
								  List<BluetoothGattService> list) {

		if (isFinishing() || isDestroyed())// activity已关闭
		{
			Log.i(TAG, "activity is findished");
			return;
		}

		try                                  // 睡眠200毫秒
		{
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (list != null)                  // 服务列表不为空
		{
			// 使能notify
			setBLENotify(gatt, true, true);
			Log.i(TAG, "使能全部notify");
		}

		// 更新连接状态
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				tvConState.setText(R.string.already_con);
			}
		});


		// 发送广播，设备已链接并使能
		Intent intent = new Intent();
		intent.putExtra("DEVICE_OK_OBJ", device);
		intent.setAction(DeviceConfig.DEVICE_CONNECTE_AND_NOTIFY_SUCESSFUL);
		sendBroadcast(intent);

		initTimeAndVersionAndBattery();


	}


	/**
	 * 初始化电量，时间，版本号,获取全天数据
	 */
	private void initTimeAndVersionAndBattery() {
		mHandler.sendEmptyMessageDelayed(MSG_SYNC_TIME, 0);
		mHandler.sendEmptyMessageDelayed(MSG_GET_DEVICE_BATTERU, 100);
		mHandler.sendEmptyMessageDelayed(MSG_GET_DEVICE_VERSION, 200);
		mHandler.sendEmptyMessageDelayed(MSG_GET_DAY_DATA, 300);
		mHandler.sendEmptyMessageDelayed(MST_GET_ALL_HEARTREAT_DATA, 800);
		mHandler.sendEmptyMessageDelayed(MSG_GET_EACH_HOUR_DATA, 600);
		mHandler.sendEmptyMessageDelayed(MSG_GET_SLEEP_DATA, 1000);


	}


	/**
	 * 获取睡眠数据
	 *
	 */
	class GetSleepDataTask extends AsyncTask<Void, Void, Boolean>
	{
		@Override
		protected Boolean doInBackground(Void... params)
		{
			new BleDataForSleepData(MainActivity.this).getTodaySleepdata();
			return null;
		}
	}

	/**
	 * 获取全天每小时数据的异步任务
	 */
	class GetEachHourTask extends AsyncTask<Integer, Void, Boolean>
	{
		@Override
		protected Boolean doInBackground(Integer... params) {
			int a = params[0];
			switch (a)
			{
				case 1:
					new BleDataForEachHourData(MainActivity.this).getTheEcchHourData();
					break;
				case 2:
					new BleDataForDayHeartReatData(MainActivity.this).requestHeartReatDataAll();
					break;
			}
			return null;
		}
	}


	private boolean mBLENotifyOpened = false;

	protected void setBLENotify(BluetoothGatt gatt, boolean isOpen, boolean force) {

		Log.e(TAG, "setBLENotify  -bdoChecked; isOpen= " + isOpen);
		Log.e(TAG, "setBLENotify  -bdoChecked; mBLENotifyOpened= " + mBLENotifyOpened);
		if (mBLENotifyOpened == isOpen && !force) {
			return;
		}
		if (gatt == null) {
			BluetoothLeService serviceMain = BluetoothLeService.getInstance();
			if (serviceMain == null) {
				Log.e(TAG, "writeDelayValue  e1");
				return;
			}

			gatt = serviceMain.getBluetoothGatt();
			if (gatt == null) {
				Log.e(TAG, "writeDelayValue  e2");
				return;
			}
		}
		Log.e(TAG, "setBLENotify  -bdoChecked; BluetoothAdapter.getDefaultAdapter().isEnabled()= "
				+ BluetoothAdapter.getDefaultAdapter().isEnabled());
		mBLENotifyOpened = isOpen;

		if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			BluetoothGattService main = gatt
					.getService(DeviceConfig.MAIN_SERVICE_UUID);
			Log.e(TAG, "onBLEServiceFound doChecked main=" + main);
			if (main != null) {
				try {
					BluetoothGattCharacteristic characteristic = main
							.getCharacteristic(DeviceConfig.UUID_CHARACTERISTIC_NOTIFY);
					BluetoothLeService.printCharacteristicProperty(characteristic);
					BluetoothLeService.getInstance().setCharacteristicNotification(characteristic, isOpen);
					Log.i("", "使能uuid:" + characteristic.getUuid().toString()
							+ "使能状态：" + isOpen);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			BluetoothGattService hrate = gatt.getService(DeviceConfig.HEARTRATE_SERVICE_UUID);
			/**
			 List<BluetoothGattService> listS = gatt.getServices();
			 for (int i = 0; i < listS.size(); i++) {
			 TLog.i("", "服务内容：" + listS.get(i).getUuid().toString());
			 }
			 TLog.i("", "service's size" + gatt.getServices().size());

			 **/

			Log.e(TAG, "onBLEServiceFound doChecked hrate=" + hrate);
			if (null != hrate) {
				BluetoothGattCharacteristic characteristic =
						hrate.getCharacteristic(DeviceConfig.HEARTRATE_FOR_TIRED_NOTIFY);
				BluetoothLeService.getInstance().setCharacteristicNotification(characteristic, isOpen);
				Log.i("", "使能uuid:" + characteristic.getUuid().toString()
						+ "使能状态：" + isOpen);
			}
			if (isOpen) {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				BluetoothGattService oad = gatt.getService(DeviceConfig.OAD_SERVICE_UUID);
				Log.e(TAG, "onBLEServiceFound doChecked oad=" + oad);
				if (null != oad) {
					BluetoothGattCharacteristic characteristic =
							oad.getCharacteristic(DeviceConfig.OAD_Charatic_UUID6);
					BluetoothLeService.getInstance().setCharacteristicNotification(characteristic, isOpen);
					Log.i("", "使能uuid:" + characteristic.getUuid().toString()
							+ "使能状态：" + isOpen);
					Log.i("", "调用。。升级---：" + isOpen);
				}
			}

		} else {
			Log.e(TAG, "have  found service, but bt have disabled  doChecked");
		}
	}

	@Override
	public void onBLEDeviceConnected(LocalDeviceEntity device, BluetoothGatt gatt)
	{

	}

	@Override
	public void onBLEDeviceDisConnected(LocalDeviceEntity device, BluetoothGatt gatt)
	{

	}

	@Override
	public void onCharacteristicRead(LocalDeviceEntity device, BluetoothGatt gatt,
									 BluetoothGattCharacteristic characteristic, boolean success)
	{

	}


	/**
	 * app接收到手环的数据，底层调用此函数，目的在于把数据回传
	 *
	 * @param device
	 * @param gatt
	 * @param uuid
	 * @param value
	 */
	@Override
	public void onCharacteristicChanged(LocalDeviceEntity device, BluetoothGatt gatt, String uuid, byte[] value)
	{
		BleNotifyParse.getInstance().doParse(MainActivity.this, value);

	}


	/**
	 * @param device
	 * @param gatt
	 * @param characteristic
	 * @param success
	 */
	@Override
	public void onCharacteristicWrite(LocalDeviceEntity device, BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, boolean success)
	{

	}

	@Override
	public void onDescriptorRead(LocalDeviceEntity device, BluetoothGatt gatt, BluetoothGattDescriptor bd, boolean success)
	{

	}

	@Override
	public void onDescriptorWrite(LocalDeviceEntity device, BluetoothGatt gatt, BluetoothGattDescriptor bd, boolean success)
	{

	}

	@Override
	public void onNoBLEServiceFound() {

	}

	/**
	 * 设备断开时，回调此方法
	 *
	 * @param device
	 * @param showToast
	 * @param fromServer
	 */
	@Override
	public void onBLEDeviceConnecError(LocalDeviceEntity device, boolean showToast, boolean fromServer)
	{
		if(!isDestroyed() || !isFinishing())
		{
			if (BluetoothLeService.getInstance() != null && !BluetoothLeService.getInstance().isConnectedDevice()
					|| !BluetoothLeService.getInstance().isConnectingDevice())
			{
				if(!fromServer)
				{
					Log.i(TAG, "用户主动断开");
					return;	// 不继续执行
				}

				// 自动连接设备

				connectTheSaveDevice();
				Log.i(TAG, "非主动断开， 以进行重新连接");





				//	设备已断开
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						tvConState.setText(R.string.not_onn);
						tvBattery.setText("X");
					}
				});
				LocalDataSaveTool.getInstance(MainActivity.this).writeSp(MyConfingInfo.HARD_VERSION, "");
				Intent intent = new Intent();
				intent.setAction(MyConfingInfo.ON_DEVICE_STATE_CHANGE);
				intent.putExtra("DEVICE_OBJ", device);
				sendBroadcast(intent);
			}
		}
		else
		{

		}









	}

	@Override
	public void onReadRemoteRssi(LocalDeviceEntity device, BluetoothGatt gatt, int rssi, boolean success) {

	}

	@Override
	public void onReliableWriteCompleted(LocalDeviceEntity device, BluetoothGatt gatt, boolean success) {

	}


	/**
	 * 绑定Service的回调借口的实现类
	 */


	ServiceConnection mBleServiceConnected = new ServiceConnection() {

		@Override // 开启Service后调用此抽象方法
		public void onServiceConnected(ComponentName name, IBinder service) {
			if (!BluetoothLeService.getInstance().initialize()) {
				showToast(R.string.ble_not_support, 1);
			} else {
				// 回传接口实现类
				BluetoothLeService.getInstance().addCallback(MainActivity.this);
				// 连接设备
				connectTheSaveDevice();

			}

		}

		@Override // 与service断开后调用此抽象方法
		public void onServiceDisconnected(ComponentName name) {

		}
	};

	private void connectTheSaveDevice()
	{
		ArrayList<DeviceSaveData> allDevice = (ArrayList)LocalDataBaseUtils.getInstance(MainActivity.this).getDeviceListFromDB();
		if(allDevice.size() != 0)
		{
			DeviceSaveData deviceSaveData = allDevice.get(allDevice.size() - 1);
			LocalDeviceEntity entity = new LocalDeviceEntity(deviceSaveData.getDeviceName(), deviceSaveData.getDeviceAddress(), -70, new byte[10]);
			BluetoothLeService.getInstance().connect(entity);
		}

	}


//	class BleServiceConnected implements ServiceConnection
//	{
//
//		@Override // 开启Service后调用此抽象方法
//		public void onServiceConnected(ComponentName name, IBinder service) {
//			if(!BluetoothLeService.getInstance().initialize())
//			{
//				showToast(R.string.ble_not_support, 1);
//			}
//			else
//			{
//				// 回传接口实现类
//				BluetoothLeService.getInstance().addCallback(MainActivity.this);
//			}
//
//		}
//
//		@Override // 与service断开后调用此抽象方法
//		public void onServiceDisconnected(ComponentName name) {
//
//		}
//	}


//-------------------------------------------------------------------------------------

	private int touchState = 0;
	private float moveStartX, moveStartY;
	private float moveOffsetX = 0;

	View.OnTouchListener touchListener = new View.OnTouchListener()
	{
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			if(0 != touchState)
			{
				doSubTouch(event);
			}

			switch (event.getAction())
			{
				case MotionEvent.ACTION_DOWN:
					moveStartX = event.getX();
					moveStartY = event.getY();
					break;

				case MotionEvent.ACTION_MOVE:
					moveOffsetX = event.getX() - moveStartX;
					moveStartY = event.getY() - moveStartY;


					if(Math.abs(moveOffsetX) > 10 || Math.abs(moveStartY) > 10)
					{

						Log.i(TAG, "移动方向：" + Math.abs(moveOffsetX) + "---" + Math.abs(moveStartY));
						if(Math.abs(moveOffsetX) > Math.abs(moveStartY))
						{
							touchState = 1;		// 横向事件
							// 构造down事件
//							event.setAction(MotionEvent.ACTION_DOWN);
////								event.setLocation();
//							mMenu.onTouchEvent(event);		// 传递给A页面
						}
						else
						{
							touchState = 2;		// 纵向事件
							// 构造down事件
							event.setAction(MotionEvent.ACTION_DOWN);
//								event.setLocation();
							layoutTwo.onTouchEvent(event);	// 传递给B页面

						}


					}

					break;

				case MotionEvent.ACTION_UP:
					touchState = 0;
					break;
			}

			return true;
		}
	};

	/**
	 * 获取控件对象并监听处理
	 */
	private void init()
	{
		mMenu = (SlidingMenu) findViewById(R.id.id_menu);
		layoutOne = (RelativeLayout)findViewById(R.id.slid_layout_one);
		layoutTwo = (CoordinatorLayout)findViewById(R.id.slid_layout_two);

		mLinearLayout = (LinearLayout)findViewById(R.id.slid_layout);
		mMenu.setOnTouchListener(touchListener);

		movementI = (ImageView)findViewById(R.id.movement_ii);

		stepAllTv = (TextView) findViewById(R.id.step_alls);
		calorieTv = (TextView) findViewById(R.id.calorie_all);
		targetTv = (TextView) findViewById(R.id.target_setting);
		// 读取缓存中的目标值
		String targetValue = LocalDataSaveTool.getInstance(MainActivity.this)
				.readSp(MyConfingInfo.TARGET_SETTING_VALUE);
		targetTv.setText(targetValue);
		movementTimeTv = (TextView) findViewById(R.id.movement_all);
		mileageTv = (TextView) findViewById(R.id.mileage_all);
		completeTv = (TextView) findViewById(R.id.complete_dergree);

		logOut = (TextView) findViewById(R.id.log_out);
		logOut.setOnClickListener(listener);

		bottom_left = (LinearLayout) findViewById(R.id.left_exit);
		botton_right = (TextView) findViewById(R.id.right_layout);
		botton_right.setOnClickListener(listener);
		bottom_left.setOnClickListener(listener);


		accountText = (TextView) findViewById(R.id.account_show);
		nickText = (TextView) findViewById(R.id.nick_show);


		dataList = new ArrayList<OutLineDataEntity>();
		itemAdapter = new MainPagerRecyclerAdapter(MainActivity.this, dataList);

		RecyclerView movementEvent = (RecyclerView) findViewById(R.id.main_view_outline_movement);
		movementEvent.setHasFixedSize(true);
		movementEvent.setLayoutManager(new LinearLayoutManager(this));
		movementEvent.setItemAnimator(new DefaultItemAnimator());
		movementEvent.setAdapter(itemAdapter);


		// 设置item监听
		itemAdapter.setMyOnItemClickListener(new MainPagerRecyclerAdapter.MyOnItemClickListener() {
			@Override
			public void OnClick(int position) {
				Toast.makeText(MainActivity.this, "点击了：" + position, Toast.LENGTH_SHORT).show();
				new CustomChooseTypeDialog(MainActivity.this, new CustomChooseTypeDialog.ChooseDialogCallback() {
					@Override
					public void onChoose(int Type, String sportName) {

					}
				});
			}
		});

		tvBattery = (TextView) findViewById(R.id.battery_value);
		tvConState = (TextView) findViewById(R.id.tv_the_connecte_state);

		// 透明状态栏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		// 透明导航
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);


		Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_main);
		toolbar.setTitle("");            // 设置默认标题为空
		setSupportActionBar(toolbar);    // 设置导航条
		toolbar.setOnMenuItemClickListener(menuListener);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);// 显示toolbar左侧按钮
		getSupportActionBar().setHomeButtonEnabled(true);


		toolbar.setNavigationIcon(R.drawable.three_line);      // 监听左侧按钮
		toolbar.setNavigationOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mMenu.toggle();
			}
		});


		// 启动设备管理页面
		device_adm = (RelativeLayout) findViewById(R.id.rl_1);
		device_adm.setOnClickListener(listener);
		// 启动提醒页面
		remindA = (RelativeLayout) findViewById(R.id.remind_activity);
		remindA.setOnClickListener(listener);
		// 启动关于页面
		aboutA = (RelativeLayout) findViewById(R.id.about_activity);
		aboutA.setOnClickListener(listener);
		// 启动帮助页面
		helpA = (RelativeLayout) findViewById(R.id.help_activity);
		helpA.setOnClickListener(listener);

		// 启动详情页面
		ImageView detailData = (ImageView) findViewById(R.id.today_movement);
		detailData.setOnClickListener(listener);
		// 启动目标设置
		ImageView settingTarget = (ImageView) findViewById(R.id.setting_the_target);
		settingTarget.setOnClickListener(listener);
		// 启动个人资料
//		RelativeLayout persionInfo = (RelativeLayout)findViewById(R.id.sliding_head);
		persionInfo = (CircleImageView) findViewById(R.id.img_portrait);
		persionInfo.setOnClickListener(listener);
//		byte[] bytes = getIntent().getByteArrayExtra("bitmap_icon");
//		Bitmap mBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//		Log.i(TAG, "获取到的图片对象:" + mBitmap);

		Bitmap mBitmap = SaveImageUtil.readImageFormSD(MyConfingInfo.IMAGEVIEW_SAVE_PATH + File.separator + "tmp.jpeg");
		persionInfo.setImageBitmap(mBitmap);
	}

	private void doSubTouch(MotionEvent event)
	{
		switch (event.getAction())
		{
			case MotionEvent.ACTION_DOWN:
				break;
			case MotionEvent.ACTION_MOVE:
				if(1 == touchState)
				{
//					mMenu.onTouchEvent(event);
				}
				else
				{
					layoutTwo.onTouchEvent(event);
				}




				break;
			case MotionEvent.ACTION_UP:
				if(1 == touchState)
				{
//					mMenu.onTouchEvent(event);
				}
				else
				{
					layoutTwo.onTouchEvent(event);
				}

				touchState = 0;
				break;



		}




	}

	/**
	 * 菜单监听器
	 */
	private Toolbar.OnMenuItemClickListener menuListener = new Toolbar.OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(MenuItem item) {
			switch (item.getItemId())    // 通过菜单id区分
			{
				case R.id.share_main:
					startActivity(ShareActivity.class);

					new ShotScreenForShare(MainActivity.this).takeshotScreen(MainActivity.this);
					break;
				case R.id.trend_main:
					startActivity(TrendActivity.class);
					break;
			}
			return true;
		}

//		@Override
//		public boolean onMenuItemClick(MenuItem item) {
//
//			return true;
//		}
	};

	/**
	 * 监听点击事件
	 */
	View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.rl_1:
//					startActivity(DeviceAmdActivity.class);
					launchActivity(device_adm, DeviceAmdActivity.class);
					break;
				case R.id.remind_activity:
					// 启动提醒页面
					if(BluetoothLeService.getInstance().isConnectedDevice())
					{
						launchRemindActivty(remindA);
					}
					else
					{
						MyToastUitls.showToast(MainActivity.this, R.string.not_connecte, 2);
					}
//					startActivity(RemindActivity.class);
					break;
				case R.id.help_activity:
//					startActivity(HelpActivity.class);
					launchActivity(helpA, HelpActivity.class);
					break;
				case R.id.about_activity:
					launchActivity(aboutA, AboutActivity.class);
//					startActivity(AboutActivity.class);
					break;
				case R.id.today_movement:
//					startActivity(Detail_activity.class);
					Intent intent = new Intent();
					intent.setClass(MainActivity.this, Detail_activity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					launchDetailActivity(movementI, intent);
					break;
				case R.id.setting_the_target:
					startActivity(TargetSettingActivity.class);
					break;
				case R.id.img_portrait:
					Intent mIntent = new Intent();
					mIntent.setClass(MainActivity.this, EditPersionInfoActivity.class);
					mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					mIntent.putExtra(MyConfingInfo.EDIT_OR_SHOW, MyConfingInfo.SHOW_THE_PERSION_INFO);
					mIntent.putExtra(MyConfingInfo.EDIT_PERSION, true);
					launchEditPersionInfoActivity(persionInfo, mIntent);
//					startActivity(EditPersionInfoActivity.class);
					break;
				case R.id.left_exit:
					System.exit(0);
					break;
				case R.id.right_layout:
					launchActivitys(botton_right, LoginActivity.class);
					MainActivity.this.finish();
					break;
				case R.id.log_out:
					// 注销登陆
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								logOutLogin();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}).start();

					launchActivitys(logOut, nextToLoginActivity.class);

					MainActivity.this.onBackPressed();


					break;
			}
		}
	};


	/**
	 * 注销登陆
	 */
	private void logOutLogin() throws IOException {
		URL url = null;
		try {
			url = new URL(MyConfingInfo.WebRoot + "user_loginOut");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setDoOutput(true);
		conn.setInstanceFollowRedirects(true);
		conn.setReadTimeout(6 * 1000);
		conn.setUseCaches(false);
		conn.setConnectTimeout(6 * 1000);
		conn.connect();


	}


	/**
	 * 让新的Activity从小范围扩大到全屏
	 *
	 * @param aboutA
	 * @param cl
	 */
	private void launchActivity(ViewGroup aboutA, Class<?> cl) {

		ActivityOptionsCompat options = ActivityOptionsCompat.makeScaleUpAnimation(
				aboutA,    // 点击的控件
				0,            // 起始坐标x
				aboutA.getHeight() / 2,    // 起始坐标y
				aboutA.getWidth(),            // 拉伸开始的区域的大小
				aboutA.getHeight());        // 拉伸开始的区域的大小

		startNewActivityOptions(options, cl);
	}

	/**
	 * 让新的Activity从小范围扩大到全屏
	 *
	 * @param aboutA
	 * @param cl
	 */
	private void launchActivitys(TextView aboutA, Class<?> cl) {

		ActivityOptionsCompat options = ActivityOptionsCompat.makeScaleUpAnimation(
				aboutA,    // 点击的控件
				0,            // 起始坐标x
				aboutA.getHeight() / 2,    // 起始坐标y
				aboutA.getWidth(),            // 拉伸开始的区域的大小
				aboutA.getHeight());        // 拉伸开始的区域的大小

		startNewActivityOptions(options, cl);
	}


	/**
	 * 设置关联动画启动Acitvity
	 *
	 * @param persionInfo
	 */
	private void launchEditPersionInfoActivity(CircleImageView persionInfo, Intent mIntent) {
		ActivityOptionsCompat compat =
				ActivityOptionsCompat.makeSceneTransitionAnimation(
						this,
						persionInfo,
						getString(R.string.image));


		ActivityCompat.startActivity(this, mIntent,
				compat.toBundle());
	}



	/**
	 * 设置关联动画启动Acitvity
	 *
	 * @param
	 */
	private void launchDetailActivity(ImageView view, Intent mIntent) {
		ActivityOptionsCompat compat =
				ActivityOptionsCompat.makeSceneTransitionAnimation(
						this,
						view,
						getString(R.string.movement_image));


		ActivityCompat.startActivity(this, mIntent,
				compat.toBundle());


	}

	private void launchRemindActivty(RelativeLayout remindA) {
		// 让新的Activity从小范围扩大到全屏
		ActivityOptionsCompat options = ActivityOptionsCompat.makeScaleUpAnimation(
				remindA,    // 点击的控件
				0,            // 起始坐标x
				remindA.getHeight() / 2,    // 起始坐标y
				remindA.getWidth(),            // 拉伸开始的区域的大小
				remindA.getHeight());        // 拉伸开始的区域的大小

		startNewActivityOptions(options, RemindActivity.class);

//		ActivityOptionsCompat compat =
//				ActivityOptionsCompat.makeSceneTransitionAnimation(
//						this,
//						remindA,
//						getString(R.string.text));
//
//		ActivityCompat.startActivity(this, new Intent(this,
//						RemindActivity.class),
//				compat.toBundle());


	}

	private void startNewActivityOptions(ActivityOptionsCompat options, Class<?> cl) {
		Intent intent = new Intent(this, cl);
		intent.putExtra(MyConfingInfo.WHERE_ARE_YOU_FROM, MyConfingInfo.FROM_THE_MAINACTIVITY);
		ActivityCompat.startActivity(this, intent, options.toBundle());

	}


	/**
	 * 启动指定的class对象
	 *
	 * @param cla
	 */
	private void startActivity(Class<?> cla) {
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, cla);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 创建新任务,此任务奔溃,不会影响整体
		startActivity(intent);
	}


	/**
	 * 在xml中定义onClick属性,等同于监听
	 *
	 * @param view
	 */
	public void toggleMenu(View view) {

	}

	/**
	 * 创建选项菜单
	 *
	 * @param menu
	 * @return
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_main, menu);// 解析菜单布局
		return true;
	}


	private void showToast(int StringId, int timeState) {
		Toast.makeText(MainActivity.this, getString(StringId), timeState == 1 ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG).show();
	}
}
